package com.situ.web.service.impl;

import com.situ.web.dao.IStudentDao;
import com.situ.web.dao.impl.StudentDaoImpl;
import com.situ.web.pojo.Student;
import com.situ.web.pojo.vo.StudentVO;
import com.situ.web.service.IStudentService;
import com.situ.web.util.PageInfo;

import java.util.List;

public class StudentServiceImpl implements IStudentService {
    private IStudentDao studentDao = new StudentDaoImpl();

    @Override
    public List<Student> selectAll() {
        return studentDao.selectAll();
    }

    @Override
    public void deleteById(Integer id) {
        studentDao.deleteById(id);
    }

    /**
     * Service业务，为了完成一个复杂的操作，需要好几步流程，
     * 可能需要调用多次dao操作
     */
    @Override
    public void add(Student student) {
        List<Student> list = studentDao.selectAll();
        for (Student stu : list) {
            if (stu.getName().equals(student.getName())) {
                throw new RuntimeException("用户名重名");
            }
        }
        studentDao.add(student);
    }

    @Override
    public Student selectById(Integer id) {
        return studentDao.selectById(id);
    }

    @Override
    public void update(Student student) {
        studentDao.update(student);
    }

    @Override
    public PageInfo<Student> selectByPage(Integer pageNo, Integer pageSize) {
        //第一条sql：查询当前页的数据
        int offset = (pageNo - 1) * pageSize;
        List<StudentVO> list = studentDao.selectByPage(offset, pageSize);
        //第二条sql：查询总的数量
        int totalCount = studentDao.selectTotalCount();
        int totalPage = (int) Math.ceil((double)totalCount / pageSize);

        PageInfo<Student> pageInfo = new PageInfo(list, totalPage, pageNo, pageSize);
        return pageInfo;
    }
}
